package com.hyper_yang._01_jdbc.prob;

import org.junit.jupiter.api.Test;

import java.sql.*;

/*
   主键回填: 将新增的数据，数据库生成主键之后，可以将主键值回传给java程序
 */
public class KeyTest {
    @Test
    public void testKey() throws SQLException {
        Connection connection = DriverManager.getConnection("jdbc:mysql:///test1", "root", "abc123");

        String sql = "insert into t_img(id,name,avatar) values(?,?,?)";
        // todo: 主键回填  Statement.RETURN_GENERATED_KEYS
        // 告诉 mysql，当前这条数据生成的主机值，需要回传给 java程序
        PreparedStatement preparedStatement = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);

        preparedStatement.setInt(1, 0);
        preparedStatement.setString(2, "name");
        preparedStatement.setObject(3, "测试主键回填");

        preparedStatement.execute();
        // 获取返回的该条数据的主键值
        ResultSet generatedKeys = preparedStatement.getGeneratedKeys();

        while (generatedKeys.next()) {
            Object key = generatedKeys.getObject(1);
            System.out.println(key);
        }

        generatedKeys.close();
        preparedStatement.close();
        connection.close();
    }
}
